//app.js
const utils = require('utils/util.js')
import { globalApis, bindingWechat, operInformation, designId } from './config/config.js'
App({
  onLaunch: function (opt) {
    wx.getSystemInfo({
      success: (res) => {
        this.globalData.height = res.statusBarHeight
      }
    })
    let res = wx.getMenuButtonBoundingClientRect()
    this.globalData.capsuleHeight = res.height
    this.globalData.capsuleWidth = res.width
    //
    this.getAccountInfoSync()

    this.globalData.sceneValue = opt.scene
    //获取设备信息
    this.getSystemInfo();
    this.setNavBarInfo()
    wx.hideTabBar()

    let that = this
  
    //扫码进来后获取参数
    if (opt) {
      let _qry = opt.query
      if (_qry.scene) {
        that.globalData.query = decodeURIComponent(_qry.scene)
      }
      that.globalData.authToPage = opt.path
    }
    //小程序强制更新
    if (wx.getUpdateManager) {
      const updateManager = wx.getUpdateManager()
      updateManager.onCheckForUpdate(function (res) {
        // 请求完新版本信息的回调
      })
      updateManager.onUpdateReady(function () {
        wx.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否重启应用？',
          success: function (res) {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              wx.clearStorageSync()
              updateManager.applyUpdate()
            }
          }
        })
      })
      updateManager.onUpdateFailed(function () {
        // 新的版本下载失败
      })
    }
    // 登录
    this.getWxUserLogin()
  },
  onShow: function () {

  },
  //获取父组件当前页
  getPrePage(){
    let pages=getCurrentPages()
    return pages[pages.length-1]
  },
  // 获取系统信息
  getSystemInfo: function () {
    let t = this;
    wx.getSystemInfo({
      success: function (res) {
        t.globalData.systemInfo = res;
        t.globalData.statusBarHeight = res.statusBarHeight
        t.globalData.screenWidth = res.screenWidth
        t.globalData.screenHeight = res.screenHeight
      }
    });
  },
  /**
 * @description 设置导航栏信息
 */
 setNavBarInfo() {
    // 获取系统信息
    const systemInfo = wx.getSystemInfoSync();
    // 胶囊按钮位置信息
    const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
    // console.log('menuButtonInfo',  menuButtonInfo)

    // 导航栏高度 = 状态栏到胶囊的间距（胶囊距上距离-状态栏高度） * 2 + 胶囊高度 + 状态栏高度
    this.globalData.navHeight = (menuButtonInfo.top - systemInfo.statusBarHeight) * 2 + menuButtonInfo.height + systemInfo.statusBarHeight;
    this.globalData.menuBotton = menuButtonInfo.top - systemInfo.statusBarHeight;
    this.globalData.menuRight = systemInfo.screenWidth - menuButtonInfo.right;
    this.globalData.menuHeight = menuButtonInfo.height;
  },
  //获取账号信息wx.getAccountInfoSync()
  getAccountInfoSync(){
    const accountInfo = wx.getAccountInfoSync();
    const appId = accountInfo.miniProgram.appId
    wx.setStorageSync('appId',appId)
  },
  // 用户登录获取openid
  getWxUserLogin() {
    // !wx.getStorageSync('openId') || wx.getStorageSync('openId') == '' || wx.getStorageSync('wechatcode')=== null
    if (true){
      wx.login({
        success: res => {
          let code = JSON.parse(JSON.stringify(res.code))
          // let appId = wx.getStorageSync('appId')
          // let secret = '3ae45628b8192922fb2b88324713e35b'
          wx.setStorageSync('wechatcode',res.code)
          wx.request({
            url: globalApis.GetisRegister+`${code}`,
            method: "GET",
            success:res=>{
              if(res.statusCode === 200){
                if(res.data.data.isRegister==='0'){
                  let {openId,session_key,unionId} = res.data.data
                  wx.setStorageSync('openId',openId)
                  wx.setStorageSync('session_key',session_key)
                  wx.setStorageSync('unionid',unionId)
                  this.globalData.openIdHandler()
                }else if(res.data.data.isRegister==='1'){
                  let userInfo = res.data.data
                  let {openId,session_key,unionId,phone} = userInfo
                  wx.setStorageSync('openId',openId)
                  wx.setStorageSync('session_key',session_key)
                  wx.setStorageSync('unionid',unionId)
                  wx.setStorageSync('userInfo',userInfo)
                  wx.setStorageSync('phone',phone)
                  this.globalData.openIdHandler()
                }
              }
            }
          })
        },
        fail(res) {
          console.log(res)
        }
      })
    }
  },

  getAuserInfo(openId){
    const params = {
      openId: openId
    }

    utils.$http(globalApis.GetAuserInformation, params,"GET",false,"JSON").then(({success,data})=>{
       if(success === 1){
         const { telephone, avatarUrl, nickName, gender, country, city, province} = data
         const userInfo = {
           avatarUrl: avatarUrl,
           city: city,
           country: country,
           gender: gender,
           nickName: nickName,
           province: province
         }
         wx.setStorageSync('phone', telephone)
         wx.setStorageSync('userInfo', userInfo)
         this.globalData.userInfoHandler()
         
       }
    })

  },
  //跳去授权页
  gotoAuth() {
    console.log('授权我来了....')
    // wx.redirectTo({
    //   url: '/pages/authorize/authorize'
    // })
  },
  //发送用户信息到后台, 传参使用es6解构赋值语法
  sendUserInfo({ code, encryptedData, iv, wxNickName, wxPhoto }) {
    var that = this;
    let param = {
      code,
      encryptedData,
      iv
    }
    utils.$http(bindingWechat, param, 'POST', true, 'JSON').then(res => {
        console.log('res:', res)
        if (res.code == '1001') {
          that.globalData.userInfo = res.data
          // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
          // 所以此处加入 callback 以防止这种情况
          if (that.userInfoReadyCallback) {
            that.userInfoReadyCallback(that.globalData.userInfo)
          }
          utils.globalShowTip(false)
          that.faBulous()
        } else {
          utils.showToast(true, res.message)
        }
      }).catch(res => {
        console.log('鉴权失败信息', res)
        utils.globalShowTip(false)
      })
  },

  isSelectCase:false,

  globalData: {
    api: globalApis,
    isIphoneX:  wx.getSystemInfoSync().safeArea.top > 20 && wx.getSystemInfoSync().model.indexOf('iPhone') > -1 ? true : false,  // 判断苹果11及以上型号手机
    isIphone: wx.getSystemInfoSync().model.search('iPhone') > -1 ? true : false,
    authInfo:null,
    userInfo: {},
    listData: [],
    authToPage: '',
    fabulous: '',
    collected: '',
    openid:'',
    toCrmPage:'',
    isTabBar:true,
    statusBarHeight: 20,
    navHeight: wx.getSystemInfoSync().model.search('iPhone') > -1 ? 40 : 42,
    navBarHeight: 0, // 导航栏高度
    menuBotton: 0, // 胶囊距底部间距（保持底部间距一致）
    menuRight: 0, // 胶囊距右方间距（方保持左、右间距一致）
    menuHeight: 0, // 胶囊高度（自定义内容可与胶囊高度保证一致）

    openIdHandler:Function,
    userInfoHandler:Function,
    screenHeight:'',
    sceneValue:1001,
    pageSize: 4,
  
  }
})